package com.hbt.myplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbt.myplus.auth.WXCore;
import com.hbt.myplus.auth.jwt.JWTUtil;
import com.hbt.myplus.model.Doctor;
import com.hbt.myplus.service.impl.DoctorServiceImpl;
import com.hbt.myplus.socket.ChatSocket;
import com.hbt.myplus.utils.ResponseWeb;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class MyController {

    @Autowired
    DoctorServiceImpl doctorService;



    @GetMapping("/abc")
    public String abc(@RequestHeader(value = "openid", defaultValue = "a") String code){
        System.out.println("a".equals(code)? "code a":code);
        return code;
    }

    String app_secret = "a1f96292cb985a542d4d832f804a0dd3";

    String appid = "wx9cab1554501087f3";

    @Autowired
    RestTemplate restTemplate;
    private String session_key;

    @GetMapping("/session/{code}")
    public String func(@PathVariable("code") String code){
        System.out.println(code);
//        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+app_secret+"&js_code="+code+"&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session?";
        Map<String, Object> wres = new HashMap<String, Object>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        wres.put("appid", appid);
        wres.put("secret", app_secret.trim());
        wres.put("js_code", code);
        wres.put("grant_type", "authorization_code");
        MultiValueMap map = new LinkedMultiValueMap();
        for(Iterator<Map.Entry<String, Object>> itr = wres.entrySet().iterator(); itr.hasNext();){
            Map.Entry<String, Object> entry = itr.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            map.add(key, value);
        }
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        try {
            ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            System.out.println("res.body:"+res.getBody());
//            session_key = (String) res.getBody().get("session_key");
            JSONObject jsonObject = JSONObject.fromObject(res.getBody());
            System.out.println("key:"+jsonObject.get("session_key"));
            session_key = (String) jsonObject.get("session_key");
            System.out.println(jsonObject.toString());
            return jsonObject.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return "body";
    }


    @GetMapping("decode")
    public String decode(@RequestParam("encry") String encry, @RequestParam("iv")String iv){
        System.out.println("encry:"+encry);
        System.out.println("iv:"+iv);
        String s = WXCore.decrypt(appid, encry,session_key,iv);
        System.out.println("解密结果"+s);
        return s;
    }


    @PostMapping(value = "/doctor/login")
    public ResponseWeb login(@RequestBody Doctor doctor){
//        return new ResponseWeb(doctorService.getById(id));
        Doctor doc = doctorService.getOne(new QueryWrapper<Doctor>().
                eq("id", doctor.getId()).eq("password", doctor.getPassword()));
        if (doc == null){
            return ResponseWeb.fail("登录失败，找不到该医生");
        }
        Map<String, String> map = new HashMap<>(); //用来存放payload信息
        map.put("id",doc.getId().toString());
        map.put("realname",doc.getRealname());
        map.put("avatar",doc.getAvatar());

        // 生成token令牌
        String token = JWTUtil.generateToken(map);
        doc.setToken(token);
        return new ResponseWeb(doc);
    }

    @GetMapping(value = "/socket/all")
    public ResponseWeb getAllSocket(@RequestParam("type") String type){
        if ("doc".equals(type)){
            return new ResponseWeb(ChatSocket.socket_list.stream().filter(a -> a.isDoc()).collect(Collectors.toList()));
        }else if ("pet".equals(type)){
            return new ResponseWeb(ChatSocket.socket_list.stream().filter(a -> !a.isDoc()).collect(Collectors.toList()));
        }else {
            return new ResponseWeb(ChatSocket.socket_list);
        }
    }


}
